package com.thirtydays.frame.base.http.okhttp

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.thirtydays.frame.base.http.okhttp.CustomGsonRequestBodyConverter
import com.thirtydays.frame.base.http.okhttp.CustomResponseConverter
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.Type

/**
 * @创建者：小垚
 * @时间：2021/8/1615:02
 * @描述：自定义解析类
 */
class CustomGsonConverterFactory(gson: Gson) : Converter.Factory() {
    private val mGson = gson

    companion object {
        fun create(): CustomGsonConverterFactory {
            return create(Gson())
        }

        fun create(gson: Gson): CustomGsonConverterFactory {
            return CustomGsonConverterFactory(gson)
        }
    }

    override fun responseBodyConverter(type: Type, annotations: Array<out Annotation>, retrofit: Retrofit): Converter<ResponseBody, *> {
        var adapter = mGson.getAdapter(TypeToken.get(type))
        return CustomResponseConverter(mGson, adapter, type)
    }

    override fun requestBodyConverter(
        type: Type,
        parameterAnnotations: Array<out Annotation>,
        methodAnnotations: Array<out Annotation>,
        retrofit: Retrofit
    ): Converter<*, RequestBody> {
        var adapter = mGson.getAdapter(TypeToken.get(type))
        return CustomGsonRequestBodyConverter(mGson, adapter)
    }

}